package com.glgc.projecti.common;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateTimeConverter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.beanutils.converters.SqlTimestampConverter;

/**
 * 对象属性对拷贝工具类
 * 
 * @author gavin
 */
public class CopyUtils
{
	public static void copyProperty(Object destObj, Object sourceObj) throws IllegalAccessException, InvocationTargetException
	{
		ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
		ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
		DateConverter dateConverter = new DateConverter(null);// 实力㈠个日期转换类
//		dateConverter.setPatterns(new String[]{"YYYY-MM-DD"});  
		ConvertUtils.register(dateConverter, Date.class);// 注册㈠个日期类
		
		BeanUtils.copyProperties(destObj, sourceObj);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void deepCopyList(List dest, List src) throws IllegalAccessException, InvocationTargetException
	{
		for (int i = 0; i < src.size(); i++)
		{
			Object obj = src.get(i);
			if (obj instanceof List)
			{
				dest.add(new ArrayList());
				deepCopyList((List) obj, (List) ((List) dest).get(i));
			} else
			{
				Object destObject = new Object();
				copyProperty(destObject, obj);
				dest.add(destObject);
			}
		}
	}
}

class DateConverter extends DateTimeConverter {  
	  
    public DateConverter() {  
    }  
  
    public DateConverter(Object defaultValue) {  
        super(defaultValue);  
    }  
  
    /* (non-Javadoc) 
     * @see org.apache.commons.beanutils.converters.AbstractConverter#getDefaultType() 
     */  
    @SuppressWarnings("rawtypes")  
    protected Class getDefaultType() {  
        return Date.class;  
    }  
  
    /* 
     * (non-Javadoc) 
     * @see org.apache.commons.beanutils.converters.DateTimeConverter#convertToType(java.lang.Class, java.lang.Object) 
     */  
    @SuppressWarnings("rawtypes")  
    @Override  
    protected Object convertToType(Class arg0, Object arg1) throws Exception {  
        if (arg1 == null) {  
            return null;  
        }  
        String value = arg1.toString().trim();  
        if (value.length() == 0) {  
            return null;  
        }  
        return super.convertToType(arg0, arg1);  
    }  
}  
